/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        return merge(lists,0,lists.size()-1);

    }
    ListNode* merge(vector<ListNode*>&lists,int left,int right)
    {
        if(left>right)return nullptr;
        if(left==right)return lists[left];
        int mid=(left+right)>>1;
        ListNode* l1=merge(lists,left,mid);
        ListNode* l2=merge(lists,mid+1,right);
        return mergeTowlist(l1,l2);
    }
    ListNode* mergeTowlist(ListNode* l1,ListNode* l2)
    {
        if(l1==nullptr)return l2;
        if(l2==nullptr)return l1;
        ListNode head;
        ListNode* cur1=l1,*cur2=l2,*prev=&head;
        head.next=nullptr;
        while(cur1&&cur2)
        {
            if(cur1->val<=cur2->val)
            {
                prev=prev->next=cur1;
                cur1=cur1->next;
            }
            else
            {
                prev=prev->next=cur2;
                cur2=cur2->next;
            }
        }
        if(cur1)prev->next=cur1;
        if(cur2)prev->next=cur2;
        return head.next;
    }
};
